<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/16 0016
 * Time: 11:24
 */
namespace app\wx_api\ext\we_chat;

use app\common\helper\RequestByCurl;
use app\common\model\ErrorModel;
use think\Exception;

/**
 * 调用微信接口获取微信用户的信息
 *
 * Class AuthToken
 * @package app\common\ext\we_chat
 */
class UserMsg {
    public $err_msg = null;
    // 获取用户详情的微信api
    const USER_INFO_API = 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN';
    // 获取用于获取用户详情的access_token的api
    const USER_TOKEN_FOR_INFO = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    // 调用微信接口获取微信的用户详情
    public function userInfo($openid, $user_token) {
        $user_info_api = self::USER_INFO_API;
        $user_info_url = sprintf($user_info_api, $user_token, $openid);

        $res = RequestByCurl::https_request($user_info_url);
        $user_info_res = json_decode($res, true);
        if (isset($user_info_res['errcode'])) { // 请求出错，记录error错误日志
//            $errM = new ErrorModel();
//            $errM->addError($user_info_res['errcode'] . $user_info_res['errmsg'], 'get_user_info_error');
            $this->err_msg = 'errcode: ' . $user_info_res['errcode'] . ',errmsg:' . $user_info_res['errmsg'];
            return false;
        }
        return $user_info_res;
    }

    // 获取用于调用微信接口获取用户详情的token
    public function userToken($code, $wx_id) {
        // 获取access_token的接口调用
        $access_token_api = self::USER_TOKEN_FOR_INFO;
        $wx_config =  WXConfig::wxConfig($wx_id);
        if (empty($wx_config)) {
            $this->err_msg = '微信配置缺失';
            return false;
        }
        $app_id = $wx_config['app_id'];
        $secret = $wx_config['secret'];
        $api_url = sprintf($access_token_api, $app_id, $secret, $code);
        $res = RequestByCurl::https_request($api_url);
        $res_data = json_decode($res, true);

        //$errM = new ErrorModel();
        if (isset($res_data['errcode'])) {
            $this->err_msg = 'errcode: ' . $res_data['errcode'] . ',errmsg:' . $res_data['errmsg'];
            //$errM->addError($res_data['errcode'] . $res_data['errmsg'], 'get_access_toke_error');
            return false;
        }
        return $res_data;
    }



}